package edu.mapi.aamas.behaviors;

import jade.core.Agent;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.FailureException;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.RefuseException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.ContractNetResponder;
import edu.mapi.aamas.common.Proposal;
import edu.mapi.aamas.common.Task;
import edu.mapi.aamas.uav.UavAgent;
/**
 * @author ZP
 */
public class TaskResponder extends ContractNetResponder {

	//private static MessageTemplate template = MessageTemplate.and(
	//  		MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET),
	//  		MessageTemplate.MatchPerformative(ACLMessage.CFP) );

	private UavAgent agent;
	private Task task = new Task();
	
	private static MessageTemplate createTemplate(Agent myAgent) {
		return MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CFP), MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET));
		
		/*try {
			TopicManagementHelper topicHelper = (TopicManagementHelper) myAgent.getHelper(TopicManagementHelper.SERVICE_NAME);
			AID stateTopic = topicHelper.createTopic("tasks");				
			topicHelper.register(stateTopic);
			
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		*/
	}
	
	public TaskResponder(UavAgent agent) {
		super(agent, createTemplate(agent));
		this.agent = agent;		
	}	
	
	protected ACLMessage prepareResponse(ACLMessage cfp) throws NotUnderstoodException, RefuseException {
		
		System.err.println("\nAgent "+agent.getLocalName()+": CFP received from "+cfp.getSender().getName());		
		ACLMessage propose = cfp.createReply();

		propose.setPerformative(ACLMessage.PROPOSE);
		try {
			task = (Task) cfp.getContentObject();			
			propose.setContentObject(agent.generateProposal(task));			
		}
		catch (Exception e) {
			e.printStackTrace();
			throw new RefuseException(e.getMessage());
		}
		return propose;		
	}
	
	protected ACLMessage prepareResultNotification(ACLMessage cfp, ACLMessage propose,ACLMessage accept) throws FailureException {
		System.out.println("Agent "+agent.getLocalName()+": Proposal accepted");
		try {
			if (((Proposal)accept.getContentObject()).taskId.equalsIgnoreCase(task.getId())) {
				agent.getPendantTasks().add(task);
				//System.out.println("Task added");
			}
			else {
				//System.err.println("Task not added!");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		ACLMessage inform = accept.createReply();
		inform.setPerformative(ACLMessage.INFORM);
		return inform;			
	}
	
	protected void handleRejectProposal(ACLMessage cfp, ACLMessage propose, ACLMessage reject) {
		System.err.println("Agent "+agent.getLocalName()+": Proposal rejected");
	}
	
	
}
